package com.tzkyzj.tiremanager.repository;



import com.tzkyzj.tiremanager.entity.CostRecord;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

@Repository
public interface CostRecordRepository extends JpaRepository<CostRecord, Long> {

    // 根据条件查询费用记录
    @Query("SELECT c FROM CostRecord c WHERE " +
            "(:company IS NULL OR c.transportCompany = :company) AND " +
            "(:startDate IS NULL OR c.costDate >= :startDate) AND " +
            "(:endDate IS NULL OR c.costDate <= :endDate) AND " +
            "(:costType IS NULL OR c.costType = :costType)")
    Page<CostRecord> findByConditions(@Param("company") String company,
                                      @Param("startDate") LocalDate startDate,
                                      @Param("endDate") LocalDate endDate,
                                      @Param("costType") String costType,
                                      Pageable pageable);

    // 统计总费用
    @Query("SELECT COALESCE(SUM(c.amount), 0) FROM CostRecord c WHERE " +
            "(:company IS NULL OR c.transportCompany = :company) AND " +
            "(:startDate IS NULL OR c.costDate >= :startDate) AND " +
            "(:endDate IS NULL OR c.costDate <= :endDate)")
    BigDecimal getTotalCost(@Param("company") String company,
                            @Param("startDate") LocalDate startDate,
                            @Param("endDate") LocalDate endDate);

    // 按类型统计费用
    @Query("SELECT c.costType, COALESCE(SUM(c.amount), 0) FROM CostRecord c WHERE " +
            "(:company IS NULL OR c.transportCompany = :company) AND " +
            "(:startDate IS NULL OR c.costDate >= :startDate) AND " +
            "(:endDate IS NULL OR c.costDate <= :endDate) " +
            "GROUP BY c.costType")
    List<Object[]> getCostByType(@Param("company") String company,
                                 @Param("startDate") LocalDate startDate,
                                 @Param("endDate") LocalDate endDate);

    // 获取运输公司列表
    @Query("SELECT DISTINCT c.transportCompany FROM CostRecord c WHERE c.transportCompany IS NOT NULL")
    List<String> findDistinctTransportCompanies();
}
